package web

import (
	"embed"
	"io/fs"
	"net/http"

	"gitee.com/dingiyan/goMyAdmin/web/api"
	"github.com/gin-gonic/gin"
)

//go:embed dist
var staticFrontend embed.FS

//go:embed dist/index.html
var staticIndexHTML []byte

// 注意//和go:embed注释不能有空格 ，只能包内目录

// 初始化所有路由
func InitRouter(ginApp *gin.Engine) {
	// static file
	ss, _ := fs.Sub(staticFrontend, "dist")
	ginApp.StaticFS("/goMyAdmin", http.FS(ss))
	ginApp.GET("/", Index)
	ginApp.POST("/api/login", api.Login)
	ginApp.GET("/api/logout", api.Logout)
	ginApp.GET("/api/getUserInfo", api.GetUserInfo)

	//
	ginApp.GET("/api/getDatasourcesRecordList", api.GetDatasourcesRecordList)
	ginApp.POST("/api/saveDatasourcesRecord", api.SaveDatasourcesRecord)
	ginApp.POST("/api/datasources/deleteDatasourcesRecord", api.DeleteDatasourcesRecord)

	ginApp.GET("/api/databases/getDatabases", api.GetDatabaseList)
	ginApp.POST("/api/databases/createDatabase", api.CreateDatabase)
	ginApp.POST("/api/databases/dropDatabase", api.DropDatabase)

	ginApp.POST("/api/tables/getTableList", api.GetTableList)
	ginApp.POST("/api/tables/createTable", api.CreateTable)
	ginApp.POST("/api/tables/renameTable", api.RenameTableName)
	ginApp.POST("/api/tables/dropTable", api.DropTable)

	ginApp.POST("/api/fields/getFields", api.GetTableFileds)
	ginApp.POST("/api/fields/addOneField", api.AddTableFileds)
	ginApp.POST("/api/fields/updateOneField", api.UpdateTableFileds)
	ginApp.POST("/api/fields/deleteOneField", api.DropTableFileds)

	ginApp.POST("/api/execRawSql", api.ExecuteSql)
}

// 首页采用这种方式output，实现不用重定向即可进入系统，不用加path goMyAdmin
func Index(c *gin.Context) {
	c.Status(http.StatusOK)
	c.Writer.Write(staticIndexHTML)
	c.Header("Content-Type", "text/html")
	// 以上等同于下面这行的效果
	// c.Redirect(302, "/goMyAdmin/")
}
